package com.example.webrestfulcrud.controller;

import com.example.webrestfulcrud.dao.ItemRepository;
import com.example.webrestfulcrud.exception.UserNotExistException;
import com.example.webrestfulcrud.pojo.TbItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    // 这样简单的配置就没必要放在controller中了
    /*@GetMapping("/index")
    public String page( Model model){

        model.addAttribute("hello","你好");

        return "index";
    }*/


    @PostMapping("/login")
    public ModelAndView login(@PathParam("userName") String userName,
                              @PathParam("password") String password,
                              ModelAndView modelAndView,
                              HttpSession session
    ) {

        if (!StringUtils.isEmpty(userName) && "123".equals(password)) {
            session.setAttribute("isLogin", true);
            session.setAttribute("user", userName);
            modelAndView.setViewName("redirect:/user/main.html");
        } else {
            modelAndView.addObject("msg", "用户名或密码不正确");
            modelAndView.setViewName("login");
        }
        return modelAndView;

    }

    /**
     * 虽然dashboard.html不叫main.html，但是其他controller也会调用这个main.html 叫着比较清晰
     *
     * @return
     */
    @GetMapping("/main.html")
    public ModelAndView successfullyLogin() {
        return new ModelAndView("dashboard");
    }



    @GetMapping("/testException/{userName}")
    @ResponseBody
    public String testException(@PathVariable String userName){
        if("aaa".equals(userName)){
            throw new UserNotExistException();
        }
        return "没有触发异常";
    }


}
